package cn.bluedot.framework.web;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alibaba.fastjson.JSON;

import cn.bluedot.framework.annotations.Dispatcher;
import cn.bluedot.framework.annotations.Redirect;
import cn.bluedot.framework.annotations.ResponseFile;
import cn.bluedot.framework.annotations.ResponseJson;

/**
 * 视图解析器
 * @author Administrator
 *
 */
public class ViewResolver {

	/**
	 * 视图解析
	 * @param handler
	 * @param req
	 * @param res
	 * @param data
	 * @throws IOException
	 * @throws ServletException
	 */
	public static void execute(Method method, HttpServletRequest req, HttpServletResponse res,
			Map<String, Object> data) throws IOException, ServletException {
		
		Object result = data.get("RESULT");
		Object type = data.get("TYPE");
		
		//处理登录
		if(Result.LOGIN.equals(type) && Result.SUCCESS.equals(result)) {
			//将data中数据装入session域对象中
			for (Entry<String, Object> entry : data.entrySet()) {
				req.getSession().setAttribute(entry.getKey(), entry.getValue());
	        }
		}
		
		//处理退出
		if(Result.LOGOUT.equals(type)) {
			req.getSession().invalidate();
			res.sendRedirect(req.getContextPath());
			return;
		}
		
		//处理文件上传
		
		
		//处理重定向
		if(method.isAnnotationPresent(Redirect.class)) {
			doRedirect(method, req, res, result);
			return;
		}
		//处理JSON
		if(method.isAnnotationPresent(ResponseJson.class)) {
			res.getWriter().print(JSON.toJSON(data));
			return;
		}
		//处理转发
		if(method.isAnnotationPresent(Dispatcher.class)) {
			doDispatcher(method, req, res, data, result);
			return;
		}
		// 处理文件
		if(method.isAnnotationPresent(ResponseFile.class)) {
			HSSFWorkbook wb = (HSSFWorkbook) data.get("wb");
			res.setContentType("application/vnd.ms-excel;charset=utf-8");
            res.setHeader("Content-Disposition",
                    "attachment;filename=\"" + new String(("output" + ".xls").getBytes("gb2312"), "ISO8859-1"));
            OutputStream out = res.getOutputStream();
            wb.write(out);
            out.close();
            return;

		}
		
	}

	private static void doDispatcher(Method method, HttpServletRequest req, HttpServletResponse res,
			Map<String, Object> data, Object result) throws ServletException, IOException {
		Dispatcher dispatcher = method.getDeclaredAnnotation(Dispatcher.class);
		
		String path = null;

		if(Result.SUCCESS.equals(result)) {
			path = dispatcher.success();
		} else if(Result.FAILED.equals(result)) {
			path = dispatcher.failed();
		}
		//将data中数据装入request域对象中
		for (Entry<String, Object> entry : data.entrySet()) {
			req.setAttribute(entry.getKey(), entry.getValue());
		}
		
		req.getRequestDispatcher(path+".jsp").forward(req, res);
	}

	private static void doRedirect(Method method, HttpServletRequest req, HttpServletResponse res, Object result)
			throws IOException {
		Redirect redirect = method.getDeclaredAnnotation(Redirect.class);
		
		String target = null;

		if(Result.SUCCESS.equals(result)) {
			target = redirect.success();
		} else if(Result.FAILED.equals(result)) {
			target = redirect.failed();
		}
		
		res.sendRedirect(req.getContextPath()+target);
		return;
	}
	
	
}